<?php
defined('APP') or die('Do not have permission to access');

class Core_View extends BaseInit
{
    private $vars = array();
    private $layout = array();
    private $loadBody = false;

    function __construct($_layout = array(), $_loadBody = false)
    {
        parent::__construct();
        $this->layout = $_layout;
        $this->loadBody = $_loadBody;
        $this->vars["baseUrl"] = getBaseUrl();
        $this->vars["basePath"] = getBaseUrl() . 'application' . DS . 'modules' . DS . SECTION . DS . 'views' . DS . 'widgets';
    }

    public function __set($index, $value)
    {
        $this->vars[$index] = $value;
    }

    public function jsonRespon($success = false, $message = null, $data)
    {
        $respon = new stdClass();
        $respon->success = $success;
        $respon->message = $message;
        $respon->data = $data;
        echo json_encode($respon);
    }

    public function render($name, $load = true)
    {
        $fileBody = 'application' . DS . 'modules' . DS . SECTION . DS . 'views' . DS . $name . '.php';
        if (!file_exists($fileBody)) {
            die('Invalid view file : ' . $fileBody);
        }

        extract($this->vars);
        ob_start();
        foreach ($this->layout["header"] as $fileName) {
            $header = 'application' . DS . 'modules' . DS . SECTION . DS . 'views' . DS . 'widgets' . DS . $fileName . '.php';
            if (file_exists($header) && !$this->loadBody && $load)
                require $header;
        }
        require_once $fileBody;
        foreach ($this->layout["footer"] as $fileName) {
            $footer = 'application' . DS . 'modules' . DS . SECTION . DS . 'views' . DS . 'widgets' . DS . $fileName . '.php';
            if (file_exists($footer) && !$this->loadBody && $load)
                require $footer;
        }
        echo ob_get_clean();
    }
}